package com.engine.camci.travel.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.time.LocalDate;
import java.util.*;

/**
 * @author dusongsong
 * @date 2024年01月09日 14:35
 */
public class TravelUtil {
    private static BaseBean baseBean = new BaseBean();
    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    private static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param tablename
     * @param paramJson
     * @return
     */
    public static int insertModelData(String tablename, JSONObject paramJson) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        int modeid = getFormmodeid(tablename);
        String uuid = UUID.randomUUID().toString();
        String insSql = "insert into " + tablename
                + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
        if (rs.executeUpdate(insSql, params)) {
            rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
            rs1.next();
            dataid = Util.getIntValue(rs1.getString("id"));
            if (dataid > 0) {
                Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    updatesql += key + "='" + map.get(key) + "',";
                }
                if (updatesql.endsWith(",")) {
                    updatesql = updatesql.substring(0, updatesql.length() - 1);
                    updatesql += " where id=" + dataid;
                    rs.executeUpdate(updatesql);
                }
                baseBean.writeLog(">>>>>insertDetailData>>>>updatesql=" + updatesql);
                //进行权限重构
                newModeRight(1, modeid, dataid);
            }
        }
        return dataid;
    }

    /**
     * 更新明细数据
     *
     * @param tablename
     * @param paramJson
     * @return
     */
    public static boolean insertDetailData(String tablename, JSONObject paramJson) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            keyString += key + ",";
            valueString += "'" + map.get(key) + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        baseBean.writeLog(">>>>>insertDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 更新数据
     *
     * @param tablename 表名
     * @param paramJson 数据集合
     * @param dataid    更新用唯一标识
     * @return
     */
    public static boolean updateModelData(String tablename, int dataid, JSONObject paramJson) {
        RecordSet rs = new RecordSet();
        String updatesql = "update " + tablename + " set  ";
        String valuesStr = "";
        Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (valuesStr.equals("")) {
                valuesStr = key + "='" + map.get(key) + "'";
            } else {
                valuesStr += "," + key + "='" + map.get(key) + "'";
            }
        }
        updatesql += valuesStr + " where id='" + dataid + "'";
        baseBean.writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
        return rs.execute(updatesql);
    }


    /**
     * 获取建模Id
     *
     * @param tablename
     * @return
     */
    private static int getFormmodeid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = ?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return Util.getIntValue(rs.getString("id"));
    }

    /**
     * 判断是否是JSON数组
     *
     * @param fieldvalue
     * @return
     */
    public static boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 拆分日期为每一天
     *
     * @param begindate
     * @param enddate
     * @return
     */
    public static List<LocalDate> splitByDateBetween(String begindate, String enddate) {
        //开始日期
        LocalDate beginDate = LocalDate.parse(begindate);
        //结束日期
        LocalDate endDate = LocalDate.parse(enddate);
        LocalDate date = beginDate;
        List<LocalDate> dates = new ArrayList<>();
        //遍历日期
        while (!date.equals(endDate.plusDays(1))) {
            dates.add(date);
            date = date.plusDays(1);
        }
        return dates;
    }


    /**
     * 删除数据
     *
     * @param tablename 表名
     * @param dataid    更新用唯一标识
     * @return
     */
    public static boolean deleteDetailData(String tablename, String dataid) {
        RecordSet rs = new RecordSet();
        String deletesql = "delete " + tablename + " where mainid='" + dataid + "'";
        baseBean.writeLog(">>>>>deleteDetailData>>>>deletesql=" + deletesql);
        return rs.executeUpdate(deletesql);
    }

    /**
     * @param loginid
     * @return
     */
    public static String getResourceidByLoginid(String loginid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from hrmresource where loginid=?", loginid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 判断是否重复
     *
     * @param userid
     * @param begdate
     * @return
     */
    public static JSONObject isExistResourceid(String userid, String tablename, String begdate) {
        RecordSet rs = new RecordSet();
        JSONObject resultJson = new JSONObject();
        String status = "I";
        String id = "";
        String sql = "select id,tbbs from " + tablename + " where bbr=? and xcrq=?";
        rs.executeQuery(sql, userid,begdate);
        if (rs.next()) {
            id = Util.null2String(rs.getString("id"));
            String tbbs = Util.null2String(rs.getString("tbbs"));
            if("1".equals(tbbs)){
                status = "U";
            }else {
                status = "N";
            }
        }
        resultJson.put("id",id);
        resultJson.put("status",status);
        return resultJson;
    }

}
